<?php

namespace App\Jobs;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class CloseOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    public function handle()
    {
        // 判断对应的订单是否已经被支付
        // 如果已经支付则不需要关闭订单，直接退出
        if ($this->order->paid_at) {
            return;
        }
        \DB::transaction(function() {
            $this->order->update(['closed' => true, 'ship_status' => Order::SHIP_STATUS_TIME_OUT]);
            // 循环遍历订单中的商品 SKU，将订单中的数量加回到 SKU 的库存中去
            foreach ($this->order->items as $item) {
                $item->productSku->addStock($item->amount);
                if ($item->product->sold_count >= $item->amount) {
                    $item->product->decrement('sold_count', $item->amount);
                } else {
                    $item->product->update(['sold_count' => 0]);
                }
            }
            // 返回优惠券
            if ($this->order->coupon) {
                $this->order->coupon->changeUsed($this->order->user, false);
            }
        });
    }
}
